package com.ruoyi.play.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.play.config.StaticSourceConfig;
import com.ruoyi.play.domain.PostPlayJoinMember;
import com.ruoyi.play.dto.PostPlayJoinDto;
import com.ruoyi.play.mapper.PostPlayJoinMemberMapper;
import com.ruoyi.play.vo.PostPlayDetailVo;
import com.ruoyi.play.vo.PostPlayOwnerVo;
import com.ruoyi.system.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.play.domain.PostPlay;
import com.ruoyi.play.service.IPostPlayService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 活动发布Controller
 *
 * @author ruoyi
 * @date 2025-05-13
 */
@RestController
@RequestMapping("/play/playinformation")
@Slf4j
public class PostPlayController extends BaseController {
    @Autowired
    private IPostPlayService postPlayService;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private PostPlayJoinMemberMapper postPlayJoinMemberMapper;

    /**
     * 查询活动发布列表
     */
    @Anonymous
    @GetMapping("/list")
    public TableDataInfo list(PostPlay postPlay) {
        List<PostPlay> list = postPlayService.selectPostPlayList(postPlay);
        return getDataTable(list);
    }

    /**
     * 查询用户自己关联活动列表
     */
    @Anonymous
    @GetMapping("/list/user/relation")
    public TableDataInfo listByUserRelation() {
        // 获取当前登录用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 判断是否登录
        if (loginUser == null) {
            throw new ServiceException("请先登录!");
        }
        // 返回参数
        // 1.查询自己发布的帖子
        PostPlay queryParam = new PostPlay();
        queryParam.setOwnerId(loginUser.getUser().getUserId());
        List<PostPlay> ownerPlayList = postPlayService.selectPostPlayList(queryParam);
        // 通过ownerList构造返回值
        List<PostPlayOwnerVo> res = new ArrayList<>();
        ownerPlayList.forEach(item -> {
            PostPlayOwnerVo postPlayOwnerVo = new PostPlayOwnerVo();
            BeanUtils.copyProperties(item, postPlayOwnerVo);
            postPlayOwnerVo.setMe(true);
            res.add(postPlayOwnerVo);
        });
        // 2.查询自己参与的帖子
        PostPlayJoinMember queryJoinParam = new PostPlayJoinMember();
        queryJoinParam.setUserId(loginUser.getUser().getUserId());
        List<PostPlayJoinMember> joinMemberList = postPlayJoinMemberMapper
                .selectPostPlayJoinMemberList(queryJoinParam);
        // 如果当前用户参与过组队,会有组队记录
        if (CollectionUtil.isNotEmpty(joinMemberList)) {
            List<Long> joinMemberPlayIdList = joinMemberList.stream()
                    .map(PostPlayJoinMember::getPlayId)
                    .collect(Collectors.toList());
            List<PostPlay> joinPlayList = postPlayService.selectPostPlayByIds(joinMemberPlayIdList);
            // 两者必然不会重复
            joinPlayList.forEach(item -> {
                PostPlayOwnerVo postPlayOwnerVo = new PostPlayOwnerVo();
                BeanUtils.copyProperties(item, postPlayOwnerVo);
                postPlayOwnerVo.setMe(false);
                res.add(postPlayOwnerVo);
            });
        }
        return getDataTable(res);
    }

    /**
     * 导出活动发布列表
     */
    @PreAuthorize("@ss.hasPermi('play:playinformation:export')")
    @Log(title = "活动发布", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PostPlay postPlay) {
        List<PostPlay> list = postPlayService.selectPostPlayList(postPlay);
        ExcelUtil<PostPlay> util = new ExcelUtil<PostPlay>(PostPlay.class);
        util.exportExcel(response, list, "活动发布数据");
    }

    /**
     * 获取活动发布详细信息
     */
    @Anonymous
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        PostPlayDetailVo res = new PostPlayDetailVo();
        PostPlay postPlay = postPlayService.selectPostPlayById(id);
        res.setPostPlay(postPlay);
        if (postPlay != null) {
            // select userInfo
            SysUser sysUser = sysUserMapper.selectUserById(postPlay.getOwnerId());
            res.setUserInfo(sysUser);
        }
        log.info("getInfo:{}", JSONUtil.toJsonStr(res));
        return success(res);
    }

    /**
     * 新增活动发布
     */
    @Anonymous
    @Log(title = "活动发布", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PostPlay postPlay) {
        // 从SpringSecurity上下文中获取用户id
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("请先登录!");
        }
        Long userId = loginUser.getUserId();
        postPlay.setOwnerId(userId);
        Date time = postPlay.getTime();
        if (time == null) {
            postPlay.setTime(new Date());
        }
        if (postPlay.getSex() == null) {
            postPlay.setSex("男生,女生");
        }
        if (postPlay.getNumber() == null) {
            postPlay.setNumber(1L);
        }
        postPlay.setImg(StaticSourceConfig.getPlayTypeImage(postPlay.getType()));
        return toAjax(postPlayService.insertPostPlay(postPlay));
    }

    /**
     * 修改活动发布
     */
//    @PreAuthorize("@ss.hasPermi('play:playinformation:edit')")
    @Anonymous
    @Log(title = "活动发布", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PostPlay postPlay) {
        return toAjax(postPlayService.updatePostPlay(postPlay));
    }

    /**
     * 删除活动发布
     */
//    @PreAuthorize("@ss.hasPermi('play:playinformation:remove')")
    @Anonymous
    @Log(title = "活动发布", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(postPlayService.deletePostPlayByIds(ids));
    }

    @Anonymous
    @Log(title = "组队", businessType = BusinessType.DELETE)
    @PostMapping("/join")
    public AjaxResult joinPlay(@RequestBody PostPlayJoinDto joinDto) {
        // get current loginUserInfo
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("请先登录!");
        }
        // get user want to join the postPlay id
        Long playId = joinDto.getPlayId();
        if (playId == null) {
            throw new ServiceException("参数不合法!!");
        }
        PostPlay postPlay = postPlayService.selectPostPlayById(playId);
        if (postPlay == null) {
            throw new ServiceException("组队信息不存在!!");
        }
        if (postPlay.getSex() != null) {
            if (loginUser.getUser().getSex() == null) {
                return AjaxResult.error("请先完善个人性别信息!");
            }
            String loginUserSex = loginUser.getUser().getSex().equals("0") ? "男" : "女";
            if (!postPlay.getSex().contains(loginUserSex)) {
                return AjaxResult.error("性别不匹配!");
            }
        }
        if (loginUser.getUser().getUserId().equals(postPlay.getOwnerId())) {
            return AjaxResult.error("不能加入自己的活动!");
        }
        // 组队信息存在,获取锁
        String lockKey = "play_" + playId;
        RLock lock = redissonClient.getLock(lockKey);
        // 尝试上锁
        try {
            boolean locked = lock.tryLock(5, 10, TimeUnit.SECONDS);
            if (locked) {
                // 上锁成功
                // 执行增加操作
                Long joinNumber = postPlay.getJoinNumber();
                if (joinNumber + 1 > postPlay.getNumber()) {
                    return AjaxResult.error("组队人数已满!");
                }
                postPlay.setJoinNumber(joinNumber + 1);
                postPlayService.updatePostPlay(postPlay);
                PostPlayJoinMember postPlayJoinMember = new PostPlayJoinMember();
                postPlayJoinMember.setJoinTime(new Date());
                postPlayJoinMember.setPlayId(playId);
                postPlayJoinMember.setUserId(loginUser.getUserId());
                postPlayJoinMemberMapper.insertPostPlayJoinMember(postPlayJoinMember);
                return AjaxResult.success("参与组队成功!");
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 释放锁
            if (lock.isHeldByCurrentThread()) {
                // 释放锁
                lock.unlock();
            }
        }
        return AjaxResult.success();
    }
}
